package swimv2gm.client.admin;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.session.AbilityManager;
import swimv2gm.bl.session.ExistingDataException;

/**
 * Modifica i dati di una competenza.
 * 
 * @author Gallesio Matteo
 */
public class UpdateAbility extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		AbilityManager man;
		try {
			man = (AbilityManager)InitialContext.doLookup("AbilityManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}
		if (request.getSession().getAttribute("admin") == null || !(Boolean)request.getSession().getAttribute("admin")) {
			response.sendError(403);
		}

		boolean success = false;
		long cid = -1;
		try {
			cid = Long.parseLong(request.getParameter("cid"));
			try {
				success = man.editAbility(cid,request.getParameter("nome"),request.getParameter("descrizione"));
			} catch (ExistingDataException e) {
				response.sendRedirect("/SWIMv2gm/admin/EditAbility?errortype=existing&cid=" + cid);
				return;
			}
		} catch (IllegalArgumentException e) {
			success = false;
		}

		if (!success) {
			response.sendRedirect("/SWIMv2gm/admin/EditAbility?errortype=invalid&cid=" + cid);
		}
		else {
			response.sendRedirect("/SWIMv2gm/abilities/AbilityList?executed=edit");
		}
	}

}
